package com.zaimokuza.cn.service.impl;

import com.zaimokuza.cn.entity.ChartData;
import com.zaimokuza.cn.entity.statistics.ManageStatisticsData;
import com.zaimokuza.cn.entity.statistics.UserBlogStatistics;
import com.zaimokuza.cn.entity.statistics.UserFollowStatistics;
import com.zaimokuza.cn.entity.statistics.UserStatisticsData;
import com.zaimokuza.cn.mapper.StatisticsMapper;
import com.zaimokuza.cn.service.StatisticsService;
import com.zaimokuza.cn.service.UserService;
import com.zaimokuza.cn.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author zaimokuza
 */
@Service
public class StatisticServiceImpl implements StatisticsService {

    @Resource
    private UserService userService;
    @Resource
    private StatisticsMapper statisticsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void statisticUserData(String date) {
        // 删除当天记录
        statisticsMapper.deleteBatchUserRecord(date);
        // 查询各项统计信息并以用户ID为key整理到缓存map集合中
        ArrayList<UserBlogStatistics> userBlogStatisticsList = statisticsMapper.queryUserBlogStatistics(date);
        HashMap<String, UserBlogStatistics> tempBlogMap = new HashMap<>();
        for (UserBlogStatistics blogStatistic : userBlogStatisticsList) {
            tempBlogMap.put(blogStatistic.getAuthorId(), blogStatistic);
        }
        // 统计总粉丝数
        ArrayList<UserFollowStatistics> userFollowStatisticsList = statisticsMapper.queryUserFollowers(date);
        // 统计新增粉丝数
        ArrayList<UserFollowStatistics> followUpList = statisticsMapper.queryUserFollowUp(date);
        // 将新增粉丝数整理到缓存map集合中
        HashMap<String, Long> tempFollowUpMap = new HashMap<>();
        for (UserFollowStatistics statistics : followUpList) {
            tempFollowUpMap.put(statistics.getUserId(), statistics.getFollowUp());
        }
        // 遍历粉丝统计信息集合
        HashMap<String, UserFollowStatistics> tempFollowMap = new HashMap<>();
        for (UserFollowStatistics followStatistic : userFollowStatisticsList) {
            // 合并粉丝数及新增粉丝数
            followStatistic.setFollowUp(tempFollowUpMap.getOrDefault(followStatistic.getUserId(), 0L));
            // 将粉丝相关统计信息整理到缓存map集合中
            tempFollowMap.put(followStatistic.getUserId(), followStatistic);
        }
        // 查询前一天的统计信息并整理到缓存map集合中
        String yesterday = LocalDate.parse(date).minusDays(1).toString();
        ArrayList<UserStatisticsData> userStatisticsDataYesterdayList = statisticsMapper.queryUserStatisticsDataListByDate(yesterday);
        HashMap<String, UserStatisticsData> tempYesterdayMap = new HashMap<>();
        for (UserStatisticsData userStatisticsData : userStatisticsDataYesterdayList) {
            tempYesterdayMap.put(userStatisticsData.getUserId(), userStatisticsData);
        }
        // 查询所有用户ID集合
        ArrayList<String> userIdList = userService.getUserIdList();
        // 整理集合
        ArrayList<UserStatisticsData> userStatisticsDataList = new ArrayList<>();
        for (String userId : userIdList) {
            // 实例化对象
            UserStatisticsData userStatisticsData = new UserStatisticsData();
            // 填充基础信息
            userStatisticsData.setUserId(userId);
            userStatisticsData.setDate(date);
            // 博客相关统计信息
            UserBlogStatistics userBlogStatistics = tempBlogMap.get(userId);
            userStatisticsData.setBlogTotal(userBlogStatistics == null ? 0L : userBlogStatistics.getTotal());
            userStatisticsData.setLikes(userBlogStatistics == null ? 0L : userBlogStatistics.getLikes());
            userStatisticsData.setPageViews(userBlogStatistics == null ? 0L : userBlogStatistics.getPageViews());
            // 关注相关统计信息
            UserFollowStatistics userFollowStatistics = tempFollowMap.get(userId);
            userStatisticsData.setFollowers(userFollowStatistics == null ? 0L : userFollowStatistics.getFollowers());
            userStatisticsData.setFollowUp(userFollowStatistics == null ? 0L : userFollowStatistics.getFollowUp());
            // 取消关注及环比信息
            UserStatisticsData userStatisticsDataYesterday = tempYesterdayMap.get(userId);
            userStatisticsData.setFollowDown(userStatisticsDataYesterday == null ? 0L : userStatisticsDataYesterday.getFollowers() + userStatisticsData.getFollowUp() - userStatisticsData.getFollowers());
            userStatisticsData.setBlogTotalCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getBlogTotal() - userStatisticsDataYesterday.getBlogTotal());
            userStatisticsData.setLikesCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getLikes() - userStatisticsDataYesterday.getLikes());
            userStatisticsData.setPageViewsCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getPageViews() - userStatisticsDataYesterday.getPageViews());
            userStatisticsData.setFollowersCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getFollowers() - userStatisticsDataYesterday.getFollowers());
            userStatisticsData.setFollowUpCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getFollowUp() - userStatisticsDataYesterday.getFollowUp());
            userStatisticsData.setFollowDownCompare(userStatisticsDataYesterday == null ? 0L : userStatisticsData.getFollowDown() - userStatisticsDataYesterday.getFollowDown());
            // 将用户统计信息添加到集合中
            userStatisticsDataList.add(userStatisticsData);
        }
        // 批量存储记录
        if (userStatisticsDataList.size() > 0) {
            statisticsMapper.insertBatchUserRecord(userStatisticsDataList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void statisticManageData(String date) {
        // 删除当天记录
        statisticsMapper.deleteManageRecord(date);
        // 获取查询日期第二天的日期字符串
        String dateParam = LocalDate.parse(date).plusDays(1).toString();
        // 查询统计相关数据，用户总数，博客总数，评论总数，ip地址总数
        Long userTotal = statisticsMapper.queryUserTotal(dateParam);
        Long blogTotal = statisticsMapper.queryBlogTotal(dateParam);
        Long commentTotal = statisticsMapper.queryCommentTotal(dateParam);
        Long ipTotal = statisticsMapper.queryIpTotal(dateParam);
        // 查询登录用户数量
        Long loginUserTotal = statisticsMapper.queryLoginUserTotal(date);
        // 创建结果实例，整理相关数据
        ManageStatisticsData manageStatisticsData = new ManageStatisticsData();
        manageStatisticsData.setDate(date);
        manageStatisticsData.setUserTotal(userTotal);
        manageStatisticsData.setBlogTotal(blogTotal);
        manageStatisticsData.setCommentTotal(commentTotal);
        manageStatisticsData.setIpTotal(ipTotal);
        manageStatisticsData.setLoginRate(BigDecimal.valueOf(loginUserTotal * 1.0 / userTotal).setScale(2, RoundingMode.HALF_UP));
        // 查询前一天的统计信息
        ManageStatisticsData yesterdayData = statisticsMapper.queryMangeStatisticsDataByDate(LocalDate.parse(date).minusDays(1).toString());
        // 根据前一天的统计信息计算环比
        if (yesterdayData == null) {
            manageStatisticsData.setUserTotalCompare(userTotal);
            manageStatisticsData.setBlogTotalCompare(blogTotal);
            manageStatisticsData.setCommentTotalCompare(commentTotal);
            manageStatisticsData.setIpTotalCompare(ipTotal);
        } else {
            manageStatisticsData.setUserTotalCompare(userTotal - yesterdayData.getUserTotal());
            manageStatisticsData.setBlogTotalCompare(blogTotal - yesterdayData.getBlogTotal());
            manageStatisticsData.setCommentTotalCompare(commentTotal - yesterdayData.getCommentTotal());
            manageStatisticsData.setIpTotalCompare(ipTotal - yesterdayData.getIpTotal());
        }
        // 存储记录
        statisticsMapper.insertManageRecord(manageStatisticsData);
    }

    @Override
    public ArrayList<UserStatisticsData> getUserStatisticsData(Integer interval) {
        // 整理条件
        String userId = UserUtils.getUser().getId();
        String startTime = LocalDate.now().minusDays(interval).toString();
        String endTime = LocalDate.now().minusDays(1).toString();
        // 查询统计信息
        ArrayList<UserStatisticsData> userStatisticsDataList = statisticsMapper.queryUserStatisticsDataListByPeriod(userId, startTime, endTime);
        // 根据时间整理到缓存map中
        HashMap<String, UserStatisticsData> tempMap = new HashMap<>();
        for (UserStatisticsData userStatisticsData : userStatisticsDataList) {
            tempMap.put(userStatisticsData.getDate(), userStatisticsData);
        }
        // 整理结果集
        ArrayList<UserStatisticsData> resultList = new ArrayList<>();
        for (int i = interval; i >= 1; i--) {
            // 无任何统计信息时创建默认信息
            String time = LocalDate.now().minusDays(i).toString();
            UserStatisticsData userStatisticsData = tempMap.get(time);
            if (userStatisticsData == null) {
                userStatisticsData = new UserStatisticsData();
                userStatisticsData.setUserId(userId);
                userStatisticsData.setDate(time);
            }
            resultList.add(userStatisticsData);
        }
        // 返回
        return resultList;
    }

    @Override
    public ManageStatisticsData getManageStatisticsData(String date) {
        return statisticsMapper.queryMangeStatisticsDataByDate(date);
    }

    @Override
    public ArrayList<ChartData> getLoginRateList(String date, Integer interval) {
        ArrayList<ManageStatisticsData> manageStatisticsDataList = statisticsMapper.queryLoginRateList(LocalDate.parse(date).minusDays(interval).toString(), date);
        ArrayList<ChartData> chartDataList = new ArrayList<>();
        for (ManageStatisticsData manageStatisticsData : manageStatisticsDataList) {
            chartDataList.add(new ChartData(manageStatisticsData.getDate(), manageStatisticsData.getLoginRate()));
        }
        return chartDataList;
    }

}
